/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.flexengine.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * @author Luann R. Athayde
 * @version 1.0
 * @since 1.0
 */
public class FlexEngineStream {

    private static long msgID = 1;
    
    private final ObjectOutputStream out;
    private final ObjectInputStream  in;
    private boolean autoFlush;

    public FlexEngineStream() {
        this.in = null;
        this.out = null;
        this.autoFlush = false;
    }
    public FlexEngineStream(ObjectInputStream in, ObjectOutputStream out) {
        this.in = in;
        this.out = out;
        this.autoFlush = true;
    }
    
    public void flush() {
        try {
            out.flush();
        } catch(Exception e) {
        }
    }
    
    public boolean write(Serializable obj) {
        try {
            if( obj instanceof FlexMessage ) {
                FlexMessage msg = (FlexMessage)obj;
                msg.setId(msgID);
                msgID++;
            }
            out.writeObject(obj);
            if( isAutoFlush() ) {
                flush();
            }
            return true;
        } catch(Exception e) {
        }
        return false;
    }
    public <T> T read() {
        try {
            return (T)in.readObject();
        } catch(IOException | ClassNotFoundException e) {}
        return null;
    }
    
    public void setAutoFlush(boolean autoFlush) {
        this.autoFlush = autoFlush;
    }
    public boolean isAutoFlush() {
        return autoFlush;
    }
    
    public boolean close() {
        try {
            in.close();
            out.close();
            return true;
        } catch(IOException e) {
            return false;
        }
    }
    
}
